package com.lepu.app.fun.chat.business.chatcore;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.database.Cursor;
import android.text.TextUtils;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.LogUtilBase;
import com.lepu.app.fun.chat.bean.ChatSession;
import com.lepu.app.fun.chat.util.DbQueryRunner;
import com.lepu.app.fun.hospital.bean.HospitalDoctor;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.usercenter.bean.LoginInfo;

import org.json.JSONObject;


/**
 * Created by Administrator on 2015/12/2.
 * 在线医生
 */
public class DoctorManager {

    private final static String TAG = DoctorManager.class.getSimpleName();

    private DoctorManager() {
    }


    static class DoctorManagerHolder {
        static DoctorManager patientManager = new DoctorManager();
    }

    public static DoctorManager getInstance() {
        return DoctorManagerHolder.patientManager;
    }

    public boolean saveDoctor2DB(HospitalDoctor doctor) {
        //更新数据库，没有更新且原状态为1的 更新状态为3
        long currentTime = new Date().getTime();

        DbQueryRunner queryRunner = DbQueryRunner.getInstance();
        if (null != doctor) {
            try {
                String sql = "REPLACE into Doctor " +
                        "( HostUserID, DoctorID, DoctorName, ProfilePictureThumbnailID, " +
                        "MobilePhone) " +
                        "values(?,?,?,?,?)";

                Object params[] = {
                        TextUtils.isEmpty(LoginUtil.getUserId()) ? 0 : LoginUtil.getUserId(),
                        doctor.DoctorID,
                        doctor.DoctorName,
                        doctor.Avatar,
                        doctor.MobilePhone,
                };
                queryRunner.update(sql, params);
                //todo 12/14 医生信息有变更进行更新
                //updateChatSessionByPatient(doctor);
                return true;
            } catch (Exception e) {
                LogUtilBase.LogE(TAG, e.toString());

            }
        }
        return false;
    }


    public void updateChatSessionByPatient(HospitalDoctor doctor) {
        try {
            ChatSession chatSession = ChatDAO.getInstance().
                    getChatSession(Long.valueOf(LoginUtil.getUserId()), Long.valueOf(doctor.DoctorID));
            if (null != chatSession) {
                chatSession.setUserNickName(doctor.DoctorName);
                chatSession.setUserProfilePictureId(doctor.Avatar);
                ChatDAO.getInstance().updateChatSession(chatSession);
            }
        } catch (Exception e) {
            LogUtilBase.LogE(TAG, e.toString());
        }
    }

    /**
     * 查询医生
     *
     * @param fromUserId
     * @return
     */
    public HospitalDoctor getDoctorByID(long fromUserId) {
        try {
            String sql = "SELECT * from Doctor Where MobilePhone=?";
            String[] params = new String[]{String.valueOf(fromUserId)};
            HospitalDoctor ids = getSessionsBySql(sql, params);
            return ids;
        } catch (Exception e) {
            LogUtilBase.LogE(TAG, e.toString());
        }
        return new HospitalDoctor();
    }

    public HospitalDoctor getSessionsBySql(String sql, String[] params) {
        try {
            DbQueryRunner queryRunner = DbQueryRunner.getInstance();

            List<HospitalDoctor> doctors = queryRunner.query(sql, new DbQueryRunner.RowHandler() {
                @Override
                public Object handle(Cursor c) {
                    HospitalDoctor doctor = new HospitalDoctor();
                    doctor.Avatar = c.getString(c.getColumnIndex("ProfilePictureThumbnailId"));
                    doctor.DoctorName = c.getString(c.getColumnIndex("DoctorName"));
                    doctor.DoctorID = c.getString(c.getColumnIndex("DoctorID"));
                    doctor.HostUserID = c.getString(c.getColumnIndex("HostUserID"));
                    doctor.MobilePhone = c.getString(c.getColumnIndex("MobilePhone"));

                    return doctor;
                }
            }, params);

            return doctors.size() == 0 ? new HospitalDoctor() : doctors.get(0);
        } catch (Exception e) {
            LogUtilBase.LogD(TAG, e.toString());
        }
        return new HospitalDoctor();
    }

    /**
     * 更新doctor
     */
    public void updateDoctorID() {
        try {
            DbQueryRunner queryRunner = DbQueryRunner.getInstance();
            String updateSql = "UPDATE Doctor set HostUserID=? ";
            queryRunner.update(updateSql, new Object[]{LoginUtil.getUserId()});
        } catch (Exception e) {
            LogUtilBase.LogD(TAG, e.toString());
        }
    }

    /**
     * 提交问题
     *
     * @param request
     * @param asyncRequest
     */
    public void submitConsultQuestion(String request, AsyncRequest asyncRequest,int category,
                                      String questionID, String question) {

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            JSONObject params = new JSONObject();
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);
            params.put("UserID", LoginUtil.getUserId());
            params.put("LoginToken", LoginUtil.getLoginToken());
            
            params.put("Category", category);
            params.put("QuestionID", questionID);
            params.put("Question", question);
            map.put("ht", params);
        } catch (Exception e) {
        }
        // MainTabActivity.getInstance().showProgressDialog();
        ApiClient.http_post(Setting.updateQuestionUrl(), map, null, asyncRequest,request, false, false, false);

    }


    /**
     * 提交问题列表
     *
     * @param request
     * @param asyncRequest
     */
    public void getConsultQuestionList(String request, AsyncRequest asyncRequest, int pageIndex, int pageSize) {

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            JSONObject params = new JSONObject();
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);
            params.put("UserID", LoginUtil.getUserId());
            params.put("LoginToken", LoginUtil.getLoginToken());
            params.put("PageIndex", pageIndex);
            params.put("PageSize", pageSize);
            map.put("ht", params);
        } catch (Exception e) {
        }
        // MainTabActivity.getInstance().showProgressDialog();
        ApiClient.http_post(Setting.getQuestionListUrl(), map, null, asyncRequest,
                request, false, false, true);

    }

    /**
     * 获取在线咨询状态
     *
     * @param request
     * @param asyncRequest
     * @param questionID
     */
    public void getQuestionStatus(String request, AsyncRequest asyncRequest, String questionID) {

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            JSONObject params = new JSONObject();
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);
            params.put("UserID", LoginUtil.getUserId());
            params.put("LoginToken", LoginUtil.getLoginToken());
            params.put("QuestionID", questionID);
            map.put("ht", params);
        } catch (Exception e) {
        }
        ApiClient.http_post(Setting.getQuestionStatuUrl(), map, null, asyncRequest,
                request, false, false, true);

    }

    /**
     * 删除问题
     *
     * @param request
     * @param asyncRequest
     * @param questionID
     */
    public void deleteQuestion(String request, AsyncRequest asyncRequest, String questionID) {

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            JSONObject params = new JSONObject();
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);
            params.put("UserID", LoginUtil.getUserId());
            params.put("LoginToken", LoginUtil.getLoginToken());
            params.put("QuestionID", questionID);
            map.put("ht", params);
        } catch (Exception e) {
        }
        ApiClient.http_post(Setting.getDeleteQuestionUrl(), map, null, asyncRequest,
                request, false, true,false );
    }


}
